


let Vue 

class Store {
    constructor(option){
        console.log(option)
        this._mutations = option.mutations
        this._actions = option.actions
        this._wrappedGetters = option.getters || {}

        const computed = {}
        this.getters = {}
        
        const store = this
        
        Object.keys(this._wrappedGetters).forEach(key => {
            const fn = store._wrappedGetters[key]

            computed[key] = function() {
                return fn(store.state)
            }

            Object.defineProperty(store.getters,key,{
                get:()=>store._vm[key]
            })
        })

        this._vm = new Vue({
            data:{
                $$state:option.state
            },
            computed
        })

        this.commit = this.commit.bind(this)
        this.dispatch = this.dispatch.bind(this)
    }

    get state(){
        return this._vm._data.$$state
    }

    set state(v){
        console.error('请使用replaceState重置状态');
    }

    commit(type,payload) {
        const mutations = this._mutations[type]
        if (!mutations) {
            console.error('mutations不存在');
        }
        mutations(this.state,payload)
    }

    dispatch(type,payload) {
        const actions = this._actions[type]
        if (!actions) {
            console.error('mutations不存在');
        }
        actions(this,payload)
    }
}

function install(_Vue) {
    Vue = _Vue
    Vue.mixin({
        beforeCreate(){
            this.$options.store && (Vue.prototype.$store = this.$options.store)
        }
    })
    
}


export default { Store, install };